import { postAddress } from '@/apis/user.js';
import { getRobotStatus, pushRobotMsg, pushWxMsg } from '@/apis/robot.js';
import { getNowTime, getRepairDate } from '@/utils/utils.js';
import { offLineSignIn } from '@/apis/workOrder.js';
import { addLog } from '@/apis/repair.js';
// 
// operation	Integer	用户操作类型 0-无操作，1-打卡，2-签到，3-签退，4-记录（上传图片、文件，写文字），5-提交，6-签字，
// 无操作时传null，后端会判断给它个0，方便管理端显示	null
// planId	Long	工单id，当不是工单的轨迹时，传null	null
// recordType	Integer	记录类型：1-工单定位 2-日常定位 3-打卡定位
// 
export async function reportAddress({ longitude, latitude, operation, planId, recordType, userId }) {
	if (!userId) {
		return;
	}
	if (!longitude) {
		let locals = await getLocalInfo();
		longitude = locals.longitude;
		latitude = locals.latitude;
	}
	if (!latitude || !longitude) {
		return;
	}

	postAddress({
		longitude,
		latitude,
		operation: operation || 0,
		planId: planId || '',
		recordType: recordType || 2,
		userId
	});
}

// 自定义配件 埋点
export function addCustompartslog({ partId, planId, other, fromLocation }) {
	addLog({
		'closestPartId': partId,
		'currentPlanId': planId,
		'customPartName': other,
		'fromLocation': fromLocation,
	});
}

// 获取经纬度信息
export function getLocalInfo() {
	return new Promise((resolve) => {
		const app = getApp();
		const cachedLocation = app.globalData.localinfo || {};
		const now = Date.now();
		// #ifdef MP-WEIXIN   
		// 检查缓存是否有效（小程序环境
		if (cachedLocation.latitude && now - cachedLocation.time <= 50 * 1000 * 1) {
			return resolve(cachedLocation);
		}
		// #endif

		// 获取当前位置
		uni.getLocation({
			type: 'gcj02',
			success(res) {
				const locationData = {
					...res,
					time: now,
					onChange: false,
				};
				app.globalData.localinfo = locationData; // 更新缓存
				resolve(locationData);
			},
			fail() {
				// 如果定位失败，返回空对象
				resolve({});
			},
		});
	});
}

// 发送群消息
// data
// id:电梯id
// img:小程序卡片封面
// name:电梯名称
// planId:工单id
// planType 工单类型  1保养 2维修
// elevatorStatus 1正常(恢复) 2停梯
// date 预计恢复时间/恢复时间
// 
export function getCardOptions(data) {
	let options = [{
		type: 'image',
		width: 500,
		height: 400,
		x: 0,
		y: 0,
		url: 'https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20230524/10d689fd8daa83a5701aa311c32a5813.png',
	}];

	options.push({
		type: 'text',
		content: data.planType == 1 ? '电梯保养' : '电梯维修',
		fontSize: 32,
		color: '#0091FF',
		x: 20,
		y: 52,
	});
	let date = getRepairDate(data.elevatorStatus == 1 ? getNowTime('', true) : data.date);

	options.push({
		type: 'text',
		content: `${data.elevatorStatus == 1 ? '恢复时间' : '预计恢复时间'}：${date.date}`,
		fontSize: 24,
		color: '#333333',
		x: 20,
		y: 92,
	});

	if (data.img) {
		options.push({// 恢复 占位
			type: 'image',
			width: 460,
			height: 274,
			x: 250 - 230,
			y: 59 * 2,
			url: data.img,
			borderRadius: 22
		});
	} else {
		if (data.elevatorStatus == 1) {
			options.push({// 恢复 占位
				type: 'image',
				width: 117 * 2,
				height: 117 * 2,
				x: 250 - 117,
				y: 69 * 2,
				url: 'https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20230524/015c9b84fbf2fb5d4a4c3f5d5daea1fc.png'
			});
		} else {
			options.push({// 停梯 占位
				type: 'image',
				width: 117 * 2,
				height: 117 * 2,
				x: 250 - 117,
				y: 69 * 2,
				url: 'https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20230524/e6f4174c48e508cbe6e47c9ff8094361.png',
			});
		}
	}

	return options;
}

// 发送群消息
// data
// id:电梯id
// img:小程序卡片封面
// name:电梯名称
// planId:工单id
// planType 工单类型  1保养 2维修
// elevatorStatus 1正常(恢复) 2停梯
// date 预计恢复时间/恢复时间
// 
export function sendRobotMsg(data) {
	return new Promise(async (resolve) => {
		pushWxMsg({
			planId: data.planId,
			isStop: data.elevatorStatus
		});
		const status = await getRobotStatusFuc(data.id);
		if (!status) {
			return;
		}
		let date = getRepairDate(data.elevatorStatus == 1 ? getNowTime('', true) : data.date);

		let content = '';
		if (data.elevatorStatus != 1) {
			content = `【停梯通知】\n${data.name}，将进行${['【电梯保养】', '【电梯维修】'][(data.planType || 1) - 1]}\n预计恢复时间：${date.str}\n请合理安排乘梯时间`;
		} else {
			content = `【电梯恢复通知】\n${data.name}${['【电梯保养】', '【电梯维修】'][(data.planType || 1) - 1]}\n已恢复正常使用\n恢复时间：${date.str} `;
		}
		// console.log('content', content) 

		pushRobotMsg({
			id: data.id,
			type: 0,
			title: (data.elevatorStatus != 1 ? '【停梯通知】' : '【电梯恢复通知】') + data.name,
			content: content,
			thumbUrl: data.img, // 
			pagePath: `${data.planType == 1 ? 'pages/elevatorTask/workOrders/detail.html' : 'packPage/repDetail/repDetail.html'}?planId=${data.planId}&elevatorId=${data.id}`

		}).then(res => {
			resolve(true);
		}).catch(err => {
			resolve(false);
		});
	});
}

export function getRobotMsg(data) {
	let date = getRepairDate(data.elevatorStatus == 1 ? getNowTime('', true) : data.date);

	let content = '';
	if (data.elevatorStatus != 1) {
		content = `【停梯通知】\n${data.name}，将进行${['【电梯保养】', '【电梯维修】'][(data.planType || 1) - 1]}\n预计恢复时间：${date.str}\n请合理安排乘梯时间`;
	} else {
		content = `【电梯恢复通知】\n${data.name}${['【电梯保养】', '【电梯维修】'][(data.planType || 1) - 1]}\n已恢复正常使用\n恢复时间：${date.str} `;
	}
	// console.log('content', content) 
	return {
		id: data.id,
		type: 0,
		title: (data.elevatorStatus != 1 ? '【停梯通知】' : '【电梯恢复通知】') + data.name,
		content: content,
		thumbUrl: data.img, // 
		pagePath: `${data.planType == 1 ? 'pages/elevatorTask/workOrders/detail.html' : 'packPage/repDetail/repDetail.html'}?planId=${data.planId}&elevatorId=${data.id}`

	};
}

// 查询电梯是否需要发送群消息
export function getRobotStatusFuc(elevatorId) {
	return new Promise((resolve) => {
		getRobotStatus({ id: elevatorId }).then(res => {
			resolve(res.data == true ? true : false);
		}).catch(err => {
			resolve(false);
		});
	});
}

// 同步离线签到数据
export function updataOffLineRecord(offLineSignRecord) {
	return new Promise(async (resolve) => {
		let img = {};
		try {
			if (offLineSignRecord.signImage) {
				img = await this.http.upload(offLineSignRecord.signImage);
				if (img.data && img.data.link) {
					offLineSignRecord.signImage = img.data.link;
				}
			}

			if (offLineSignRecord.messageDTO) {
				offLineSignRecord.messageDTO = getRobotMsg(offLineSignRecord.messageDTO);
			}
		} catch (error) {
			resolve();
			return;
		}
		offLineSignRecord.finishDate = `${offLineSignRecord.finishDate}${offLineSignRecord.finishDate && offLineSignRecord.finishDate.length < 18 ? ':00' : ''}`;
		delete offLineSignRecord.messageDTO;
		console.log('全局同步离线签到', offLineSignRecord);
		offLineSignIn(offLineSignRecord).then(() => {
			uni.setStorage({
				key: 'offline_sign_record',
				data: {},
				complete: () => {
					resolve(true);
				}
			});
		});
	});
}
